package com.example.denglu.servlet;

import com.example.denglu.service.UserService;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/resetPassword")
public class ResetPasswordServlet extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        String phone = request.getParameter("phone");
        String code = request.getParameter("code");
        String newPassword = request.getParameter("newPassword");
        
        response.setContentType("application/json;charset=utf-8");
        
        // 检查手机号是否已注册
        String username = UserService.getRegisteredUsername(phone);
        if (username == null) {
            response.getWriter().write("{\"success\":false,\"message\":\"该手机号未注册\"}");
            return;
        }
        
        // 输入验证
        if (phone == null || phone.trim().isEmpty() || 
            code == null || code.trim().isEmpty() ||
            newPassword == null || newPassword.trim().isEmpty()) {
            response.getWriter().write("{\"success\":false,\"message\":\"所有字段都不能为空\"}");
            return;
        }
        
        // 重置密码
        boolean isSuccess = UserService.resetPassword(phone, newPassword, code, request.getSession());
        
        String message = isSuccess ? "密码重置成功" : "验证码错误或手机号未注册";
        response.getWriter().write("{\"success\":" + isSuccess + ",\"message\":\"" + message + "\"}");
    }
} 